import {Application, AppStatus} from '../types'
import unmountApp from "../lifeCycle/unmount";
import bootstrapApp from "../lifeCycle/bootstrap";
import mountApp from "../lifeCycle/mount";

export const apps: Application[] = []

export async function loadApps() {
	const toUnmountApp = getAppsWithStatus(AppStatus.UNMOUNTED)
	await Promise.all(toUnmountApp.map(unmountApp))

	const toLoadApp = getAppsWithStatus(AppStatus.BEFORE_BOOTSTRAP)
	await Promise.all(toLoadApp.map(bootstrapApp))

	const toMountApp = [
		...getAppsWithStatus(AppStatus.BOOTSTRAPPED),
		...getAppsWithStatus(AppStatus.UNMOUNTED)
	]

	await toMountApp.map(mountApp)
}

function getAppsWithStatus(status: AppStatus) {
	const result: Application[] = []
	apps.forEach(app => {
		if (isActive(app) && app.status === status) {
			switch (app.status) {
				case AppStatus.BEFORE_BOOTSTRAP:
				case AppStatus.BOOTSTRAPPED:
				case AppStatus.UNMOUNTED:
					result.push(app)
					break
			}
		} else if (app.status === AppStatus.BEFORE_MOUNT && status === AppStatus.MOUNTED) {
			result.push(app)
		}
	})
	return result
}

function isActive(app: Application) {
	return typeof app.activeRule === 'function' && app.activeRule(window.location)
}
